<?php

namespace App\Service\Article;

use App\Http\Resources\Article\ApiArticleListResource;
use App\Http\Resources\Article\ArticleCategoryListResource;
use App\Http\Resources\Article\ArticleListResource;
use App\Http\Resources\Article\ArticleRecommendListResource;
use App\Models\Article\ArticleCategoryModel;
use App\Models\Article\ArticleModel;
use App\Models\Article\ArticleRecommendModel;
use App\Models\BaseModel;
use App\Service\BaseService;
use Exception;

class ArticleRecommendService extends BaseService
{

    /**
     * @param object $params
     * @return array|void
     * @throws Exception
     */
    public static function list(object $params)
    {
        try {
            $paginate = ArticleRecommendModel::query()
                                             ->when(checkFieldLen($params, "type"), function ($query) use ($params) {
                                                 $query->whereIn('type', explode(",", $params->type));
                                             })
                                             ->when(!empty($params->title), function ($query) use ($params) {
                                                 $query->where('title', 'like', '%' . $params->title . '%');
                                             })
                                             ->orderBy('sort')
                                             ->orderByDesc('createdAt')
                                             ->paginate($params->pageSize, ['*'], 'pageNum', $params->pageNum);

            return [
                "list"     => ArticleRecommendListResource::collection($paginate->items()),
                "count"    => $paginate->total(),
                "pageNum"  => $params->pageNum,
                "pageSize" => $params->pageSize
            ];
        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }

    /**
     * @param object $params
     * @throws Exception
     */
    public static function add(object $params)
    {
        try {
            $insertData = (array)$params;
            if ($params->effectiveType == ArticleRecommendModel::EFFECTIVE_TYPE_LIMIT) {
                $insertData['startAt'] = strtotime($insertData['startAt']);
                $insertData['endAt']   = strtotime($insertData['endAt']);
            } else {
                $insertData['startAt'] = $insertData['endAt'] = 0;
            }

            if (empty($insertData['sort'])) {
                $insertData['sort'] = 100;
            }
            ArticleRecommendModel::query()->create($insertData);
        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }


    /**
     * @param object $params
     * @throws Exception
     */
    public static function update(object $params)
    {
        try {
            $updateData            = (array)$params;
            $id                    = $updateData['id'];


            if($params->effectiveType == ArticleRecommendModel::EFFECTIVE_TYPE_LIMIT){
                $updateData['startAt'] = strtotime($updateData['startAt']);
                $updateData['endAt']   = strtotime($updateData['endAt']);
            }else{
                $updateData['startAt'] = $updateData['endAt'] = 0;
            }

            unset($updateData['id']);
            ArticleRecommendModel::query()->where('id', $id)->update($updateData);
        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }

    /**
     * @param object $params
     * @throws Exception
     */
    public static function patch(object $params)
    {
        try {
            $updateData = (array)$params;
            $id         = $updateData['id'];
            unset($updateData['id']);
            ArticleRecommendModel::query()->where('id', $id)->update($updateData);
        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }

    /**
     * @param int $id
     * @throws Exception
     */
    public static function del(int $id)
    {
        try {
            ArticleRecommendModel::query()->where('id', $id)->update(['isDeleted' => BaseModel::DELETE_YES]);
        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }

    /**
     * @param object $params
     * @return array|void
     * @throws Exception
     */
    public static function detail(object $params)
    {
        try {
            $id     = $params->id;
            $detail = ArticleRecommendModel::query()
//                                           ->with([
//                                               'articleRel' => function ($query) {
//                                                   $query->select(['id', 'title']);
//                                               }
//                                           ])
                                           ->where('id', $id)->first();

            return [
                "detail" => ArticleRecommendListResource::collection([$detail])->getIterator()->current()
            ];
        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }


    public static function getRecommendList(array $where = [])
    {
        $list = ArticleRecommendModel::query()
                                     ->with(['articleRel'])
                                     ->when(isset($where['isActivate']), function ($query) use ($where) {
                                         $query->where('isActivate', $where['isActivate']);
                                     })
                                     ->where(function ($query) {
                                         $query->where("effectiveType",
                                             ArticleRecommendModel::EFFECTIVE_TYPE_ALWAYS)
                                               ->orWhere(function ($query) {
                                                   $query->where("effectiveType",
                                                       ArticleRecommendModel::EFFECTIVE_TYPE_LIMIT)
                                                         ->where('startAt', '<', time())
                                                         ->where('endAt', '>', time());
                                               });
                                     })
//                                     ->where('startAt', '<', time())
//                                     ->where('endAt', '>', time())
                                     ->orderBy('sort')
                                     ->orderByDesc('id')
                                     ->get();

        $resultList = [];

        foreach ($list as $item) {
            $redirectUrl = '';
            if ($item->contentType == ArticleRecommendModel::CONTENT_TYPE_CATEGORY) {
                $redirectUrl = config('open-shop.m') . "content/subject/" . $item->articleId . "?hideAppBar=true";
            } elseif ($item->contentType == ArticleRecommendModel::CONTENT_TYPE_REDIRECT_URL) {
                $redirectUrl = $item->redirectUrl ?? '';
            }
            $resultList[] = [
                'articleId'   => $item->articleId,
                'title'       => $item->title,
                'description' => $item->description,
                'cover'       => $item->cover,
                'type'        => $item->type,
                'redirectUrl' => $redirectUrl,
                "contentType" => $item->contentType,
                'article'     => $item->articleRel && $item->contentType == ArticleRecommendModel::CONTENT_TYPE_ARTICLE ?
                    ApiArticleListResource::collection([$item->articleRel])->getIterator()->current() : null
            ];
        }

        $resultList = collect($resultList);

        $result = [];


        foreach (ArticleRecommendModel::TYPE_ENG_TEXT as $key => $item) {
            $result[$item] = $resultList->where('type', $key)->values();
        }

        $defaultHomeRecommend = [
            'articleId'   => 0,
            'title'       => '无标题',
            'description' => '要跳转',
            'cover'       => 'https://file.51kuafu.com/f2/30/5bad4d6d149421e1753189892f3212a1f64de4578b382851a2321c861e83.jpg',
            'type'        => 1,
            'redirectUrl' => 'https://h5.kuafood.com/',
            'article'     => [
                'type' => 1
            ]
        ];

        $defaultSubjectRecommend1 = [
            'articleId'   => 0,
            'title'       => '中国快餐百强企业',
            'description' => '要跳转',
            'cover'       => 'https://file.51kuafu.com/5a/4d/6cf3a51c2250cbfc83087d1ab3014b67918364a80b94c0c49eba2f1c25c2.jpg',
            'type'        => 1,
            'redirectUrl' => 'https://h5.kuafood.com/',
            'article'     => [
                'type' => 1
            ]
        ];

        $defaultSubjectRecommend2 = [
            'articleId'   => 0,
            'title'       => '极致供应链',
            'description' => '要跳转',
            'cover'       => 'https://file.51kuafu.com/36/f5/480caae80849051440343f8b196689ab03dc3ee78fd4ecb994e61891e7f5.jpg',
            'type'        => 1,
            'redirectUrl' => 'https://h5.kuafood.com/',
            'article'     => [
                'type' => 1
            ]
        ];

        // 配置默认信息
        if (count($result['homeRecommend']) == 0) {
            $result['homeRecommend'][] = $defaultHomeRecommend;
        }

        if (count($result['subjectRecommend']) == 0) {
            $result['subjectRecommend'][] = $defaultSubjectRecommend1;
            $result['subjectRecommend'][] = $defaultSubjectRecommend2;
        }

        if (count($result['subjectRecommend']) == 1) {
            $result['subjectRecommend'][] = $defaultSubjectRecommend2;
        }

        if (count($result['newRecommend']) == 0) {
            $result['newRecommend'] = [];
        }

        return $result;
    }
}
